<template>
  <view class="wl-upload">
    <wd-img :width="80" :height="80" :src="imageSrc" />
    <view
      @click="handleClick"
      style="
        display: inline-flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 80px;
        height: 80px;
        background-color: #f5f5f5;
      "
    >
      <wd-icon size="30px" color="#B8B8B8" name="fill-camera"></wd-icon>
    </view>
    <!-- 用于显示选中的图片 -->
  </view>

  <wd-form ref="form" :model="model">
    <wd-cell title="留言" title-width="100px" prop="fileList">
      <wd-input
        label-width="100px"
        prop="value1"
        clearable
        v-model="model.value1"
        placeholder="请输入留言"
        :rules="[{ required: true, message: '请填写留言' }]"
      />
    </wd-cell>
    <wd-cell title="图片" title-width="100px" prop="fileList">
      <wd-upload :file-list="model.fileList" action="#" @change="handleFileChange"></wd-upload>
    </wd-cell>
    <view class="footer">
      <wd-button type="primary" size="large" @click="handleSubmit" block>提交</wd-button>
    </view>
  </wd-form>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { supabase } from '@/utils/init'

const model = reactive({
  value1: '',
  fileList: [],
})

const uuid = () => {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4()
}
// 在微信中是http://tmp/123.png 转为uuid.png
function replaceFileName(oldFileNameWithExtension, newFileName) {
  const extension = oldFileNameWithExtension.split('.').pop()
  return `${newFileName}.${extension}`
}
const imageSrc = ref(
  'https://coumbga5g6hc2l9v8nk0.baseapi.memfiredb.com/storage/v1/object/public/avatar/6e8974cdb67c961b9262142273fe39f4.jpg?t=2024-07-18T02%3A50%3A23.079Z',
)
const handleClick = async () => {
  // #ifdef MP-WEIXIN
  uni.chooseMedia({
    count: 1,
    mediaType: ['image'],
    success: async (res) => {
      console.log('111: ' + JSON.stringify(res.tempFiles[0].tempFilePath))
      const newName = replaceFileName(res.tempFiles[0].tempFilePath, uuid())
      const avatarFile = res.tempFiles[0]
      const { data, error } = await supabase.storage.from('avatar').upload(newName, avatarFile)
      console.log('111: ' + JSON.stringify(data))
      const { data: newData } = await supabase.storage.from('public-bucket').getPublicUrl(newName)
      imageSrc.value = newData.publicUrl
    },
    fail: (err) => {
      console.error('uni.chooseMedia err->', err)
      error.value = true
    },
  })
  // #endif
}
function handleFileChange({ fileList }) {
  model.fileList = fileList
  console.log(fileList)
}

const form = ref()

const handleSubmit = async () => {
  form.value
    .validate()
    .then(async ({ valid, errors }) => {
      if (valid) {
        const { error } = await supabase.from('comment').insert({
          created_at: new Date(),
          commentator: 'Shengguo',
          responder: '',
          comment_content: model.value1,
          reply_content: '',
          post_id: 1,
        })
        if (error) {
          throw error
        } else {
          uni.showToast({
            icon: 'none',
            title: '保存通过',
          })
        }
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
onMounted(() => {})
</script>

<style lang="scss" scoped>
.wl-upload button {
  /* 按钮样式 */
}
.preview-image {
  /* 预览图片样式 */
  width: 100%;
  height: auto;
}
</style>
